package com.cans.lightning.business.lowcode.manager.form.loader.tableBean;

import com.cans.lightning.business.lowcode.dto.AppTableFieldDto;
import com.cans.lightning.business.lowcode.entity.AppTable;
import com.cans.lightning.business.lowcode.manager.form.bean.FormFieldBean;
import com.cans.lightning.business.lowcode.manager.form.bean.MainTableBean;
import com.cans.lightning.business.lowcode.manager.form.loader.AbstractBeanLoader;
import com.cans.lightning.business.lowcode.service.api.IAppTableFieldService;
import com.cans.lightning.business.lowcode.service.api.IAppTableService;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cans
 * @date 2023/11/29
 **/
@Component
public class MainTableBeanLoader extends AbstractBeanLoader<MainTableBean> {

    @Resource
    private IAppTableService appTableService;
    @Resource
    private IAppTableFieldService appTableFieldService;

    @Override
    public MainTableBean loadOne(MainTableBean appTableBean) {
        if(appTableBean.getId() == null){
            appTableBean.setFieldList(Lists.newArrayList());
            return appTableBean;
        }
        AppTable appTable = appTableService.getById(appTableBean.getId());
        if(appTable != null){
            appTableBean.setFormId(appTable.getFormId());
            appTableBean.setDbTableName(appTable.getDbTableName());
            appTableBean.setTableName(appTable.getTableName());
        }
        List<AppTableFieldDto> fieldArr = appTableFieldService.getByTableId(appTableBean.getId());
        List<FormFieldBean> fieldList = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(fieldArr)) {
            fieldList = fieldArr.stream().map(i -> new FormFieldBean().create(i)).collect(Collectors.toList());
        }
        appTableBean.setFieldList(fieldList);
        return appTableBean;
    }
}
